package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	pb "gitee.com/JaneCrysteal/grpcdemo/services"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io/ioutil"
)

// NewGrpcCommonClient --
func NewGrpcCommonClient() {
	var (
		conn *grpc.ClientConn
		err  error
	)
	conn, err = grpc.Dial("localhost:8090", grpc.WithInsecure())
	if nil != err {
		return
	}
	defer conn.Close()

	goodsServerClient := pb.NewGoodsServiceClient(conn)

	goodsReq := &pb.GetGoodsReq{Oid: 1005}

	var result *pb.GoodsDataInfo
	result, err = goodsServerClient.GetGoodsInfo(context.Background(), goodsReq)
	if nil != err || nil == result {
		fmt.Println(err)
		return
	}

	fmt.Println("商品编号:", result.Oid, "商品名称:", result.Name)
}

// NewGrpcTLSClient -- Go1.15之前版本
func NewGrpcTLSClient() {
	var (
		creds credentials.TransportCredentials
		conn  *grpc.ClientConn
		err   error
	)

	creds, err = credentials.NewClientTLSFromFile("cert/server.crt", "winsun.com")
	if nil != err {
		return
	}

	conn, err = grpc.Dial(":8090", grpc.WithTransportCredentials(creds))
	if nil != err {
		return
	}

	defer conn.Close()

	goodsServerClient := pb.NewGoodsServiceClient(conn)

	goodsReq := &pb.GetGoodsReq{Oid: 1001}

	var result *pb.GoodsDataInfo
	result, err = goodsServerClient.GetGoodsInfo(context.Background(), goodsReq)
	if nil != err || nil == result {
		fmt.Println(err)
		return
	}

	fmt.Println("商品编号:", result.Oid, "商品名称:", result.Name)
}

// NewGrpcCAClient --
func NewGrpcCAClient() {
	var (
		conn  *grpc.ClientConn
		err   error
	)

	// ssl 的升级版
	cert,_:=tls.LoadX509KeyPair("cert/client.pem","cert/client.key")

	certPool:=x509.NewCertPool()

	ca,_:=ioutil.ReadFile("cert/ca.pem")

	certPool.AppendCertsFromPEM(ca)

	creds:=credentials.NewTLS(&tls.Config{
		Certificates:                []tls.Certificate{cert},// 客户端证书
		ServerName:                 "localhost",// 需要验证客户端证书(双向验证)
		RootCAs:                   certPool,
	})


	conn, err = grpc.Dial(":8090", grpc.WithTransportCredentials(creds))
	if nil != err {
		return
	}

	defer conn.Close()

	goodsServerClient := pb.NewGoodsServiceClient(conn)

	goodsReq := &pb.GetGoodsReq{Oid: 1001}

	var result *pb.GoodsDataInfo
	result, err = goodsServerClient.GetGoodsInfo(context.Background(), goodsReq)
	if nil != err || nil == result {
		fmt.Println(err)
		return
	}

	fmt.Println("商品编号:", result.Oid, "商品名称:", result.Name)

}
func main() {
	NewGrpcCAClient()
}
